captions = ["绝对位置信息读取 0x02","多圈数据信息读取 0x8A","编码器ID信息读取 0x92","读取所有数据 0x1A","读取必要数据 0x2B"]
codes = [0x02,0x8a,0x92,0x1a,0x2b]

import sys,serial,time
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QTextEdit

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        # 创建5个按钮
        for i in range(5):
            button=QPushButton(captions[i], self)
            button.clicked.connect(lambda checked=True,n=i: self.on_click(n))
            layout.addWidget(button)

        # 创建多行文字区
        self.text_edit = QTextEdit(self)
        layout.addWidget(self.text_edit)

        self.setLayout(layout)
        self.setWindowTitle('编码器读取')
        self.show()

    def on_click(self,button_number):
        sender = self.sender()
        # 打开串口，将COM3替换为你的串口号
        ser = serial.Serial('COM4', 2500000)
        ser.write(codes[button_number].to_bytes())
        # wait 100 ms 读取字节的返回值
        time.sleep(0.1)
        bufferBytes = ser.inWaiting()
        response = ser.read(bufferBytes)
        self.text_edit.append(f'{sender.text()} ：{bytes.hex(response)}')
       # 关闭串口
        ser.close() 


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

